/*
 * 该js文件专门用于存放单据通用的方法
 * */
//所有dom加载完后执行，类似页面launch
(function () {
})(jQuery);
//所有资源加载完后执行的方法
window.onload = function(){
	setTimeout(function(){//起始通过cookie判断单据是否流转
		if($.cookie('dhecp_tpTransfer')){
			$.removeCookie('dhecp_tpTransfer',{path:'/'});//优先删除提示流转cookie
			console.log("moduleTable",moduleTable)
			if($('#nid').val()!=0){//如果是制单则无需提示
				if (moduleTable !== 'THR_USERPERFORMANCERULE' && moduleTable !== 'THR_USERPERFORMANCECONDITION' && moduleTable !== 'THR_USERRANK' && moduleTable !== 'THR_USERRANKAPPLY' && moduleTable !== 'THR_USERSALARY'&& moduleTable !== 'THR_USERPAYMENTYB'&& moduleTable !== 'THR_USERPAYMENTSB'&& moduleTable !== 'THR_USERPAYMENTGJJ'&& moduleTable !== 'THR_USERWELFARE'){
					layer.confirm('已保存成功，是否流转该单据？', {
						icon: 3,
						offset: '10%',
						title: "系统提示",
						btn: ['确认', '取消'],
						success: function(layero, index){
							$(document).keydown(function (e) {//监听键盘
								switch(e.keyCode){
									case 13://回车键
										layero.find('.layui-layer-btn0').trigger("click");
										break;
									case 27://esc键
										layero.find('.layui-layer-btn1').trigger("click");
										break;
								}
							});
						},
						yes: function(index){
							layer.closeAll();
							tpBtnClick('tpTransfer');
						},
						end: function(){
							$(document).unbind('keydown');//移除监听键盘，防止其他事件被移除（如lay-tips提示监听）
						}
					});
				}
			}
		}
	}, 500);
	if(typeof ajaxResult != 'undefined' && ajaxResult.code !=0 ){
		if(ajaxResult.msg==null)ajaxResult.msg='错误信息为空！';
		$.modal.alert(ajaxResult.msg, ajaxResult.code);
	}
}
//表格初始化
function initTable(){
	var ev=nid==0?false:true;
	$.tablelist.init({
		elem: '#dhtable'
		,data: decimalToFixed(dataStr,decimalObj)
		,page: false
		,even: gridColumns.readOnly
		,limit: 9999
		,totalRow: gridColumns.totalRow
		,cols: [gridColumns.gridBody
		]
		,toolbar: (isEdit || isShow)?false:'#toolbar'//强制生成可编辑页面无需显示操作栏
		,defaultToolbar: [{title:'展开',layEvent: 'tableFull',icon: 'layui-icon-screen-full'},{title:'列设置',layEvent: 'fieldSet',icon: 'layui-icon-set'}]
		,height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+66)//高度自适应

		,done:function(res, curr, count){
			var ltv=this.elem.next('.layui-table-view');//当前table的dom
			res.data.length || count || ltv.find('.layui-table-header').css('display', 'inline-block');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
			res.data.length || count || ltv.find('.layui-table-box').css('overflow-x', 'auto');//数量为0时(统计报表存在不传count的情况)，表头赋予样式可拉动
			res.data.length || count || ltv.find('.layui-table-body').css('height', ltv.find('.layui-table-body').height()-17);//数量为0时，表格高度减少滚动条高度
			fixTotal(this);//修复合计行固定列问题
			listData = table.cache.dhtable;//每次重载都赋值更新表缓存
			if(!gridColumns.readOnly)tableDone(listData,fieldFrontEditList);//非只读情况下的动作集
			if(typeof tableAllwaysDone== 'function')tableAllwaysDone(listData);//如果单据存在不论任何情况都要执行的方法则执行
			showloadings(false);
			detailUpload();
			$(".detail-edit").prev().css({'width':'90%','display':'inline-block','overflow':'hidden'});		//防止表格中文本域编辑按钮遮挡
		}
	});
}
//明细表格中的字段遍历
function eachFields(){
	$.each(gridColumns.dictionaryForPageFieldList,function(i,v){//遍历明细中所有的字段
		// if(v.fieldFrontEdit == false && v.fieldFrontHidden == false)fieldFrontEditList.push(v.fields);//明细表格中不可编辑字段
		// if(typeof dropDownEditList != 'undefined' && v.fieldFrontEdit == true && v.fieldFrontHidden == false && v.fieldFrontType=='t_dropdownedit'){
		// 	dropDownEditList.push(v.fields);//存在下拉可编辑集合并且是下拉可编辑字段
		// }
		if(v.fieldFrontEdit == false)fieldFrontEditList.push(v.fields);//明细表格中不可编辑字段
		if(typeof dropDownEditList != 'undefined' && v.fieldFrontEdit && v.fieldFrontType=='t_dropdownedit'){//存在下拉可编辑集合并且是下拉可编辑字段
			dropDownEditList.push(v.fields);
		}
		if(v.fieldFrontEdit == true && v.fieldFrontType=='t_buttontextedit'){//可编辑弹出框，输入动态改变listdata
			var fd=v.fields;
			window.inputOnTable=function (obj,fd){
				listData[$(obj).parents('tr').index()][fd]=obj.value;
			}
		}
	});
	$.each(gridColumns.gridNewLine,function(v,k){//明细新增模板修改默认值
		if(k.substring(0,1)=='#')gridColumns.gridNewLine[v]=$(k).val();
	})
}

/*
 * 表格回调事件的动作集（单据非只读情况下）
 * param：listData 表缓存的存储对象
 * param：fieldFrontEditList 不可编辑字段field集合
 * param：isChild 
*/
function tableDone(listData,fieldFrontEditList,isChild=false){
	$(".layui-table-date").each(function (i,v) {//单据明细中的日期控件
		var elemtr = $(v).parents('tr').index();//当前下标
		var elem = $(v).parents('td');//当前单元格
		var datafield = elem.attr("data-field");//当前字段
		$(v).unbind();//清除事件，防止重复监听
		$(v).on('change',function(){//手动修改日期
			var errorMsg = '';//错误提示
			switch($(v).attr('fft')){
				case 't_date':
					if(judgeStrDate($(v).val())){//验证日期格式
						var r = $(v).val().match(/^(\d{1,4})(-|\/|.)(\d{1,2})\2(\d{1,2})$/);
						if(typeof judgeTableDate == 'function')judgeTableDate(v,formatDate(new Date(r[1], r[3]-1, r[4]),'date'),elemtr,datafield);
						else{
							$(v).val(formatDate(new Date(r[1], r[3]-1, r[4]),'date'));
							listData[elemtr][datafield] = formatDate(new Date(r[1], r[3]-1, r[4]),'date');
						}
					}else errorMsg = '请输入正确时间格式，形如2020-01-01';
					break;
				case't_datetime':
					if(judgeStrDateTime($(v).val())){//验证日期时间格式
						var r = $(v).val().match(/^(\d{1,4})(-|\/|.)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
						if(typeof judgeTableDate == 'function')judgeTableDate(v,new Date(r[1], r[3]-1, r[4], r[5], r[6], r[7]),elemtr,datafield);
						else{
							$(v).val(formatDate(new Date(r[1], r[3]-1, r[4], r[5], r[6], r[7])));
							listData[elemtr][datafield] = formatDate(new Date(r[1], r[3]-1, r[4], r[5], r[6], r[7]));
						}
					}else errorMsg = '请输入正确时间格式，形如2020-01-01 00:00:00'; 
					break;
				case 't_year':
					if(judgeStrYear($(v).val())){//验证年份格式
						var r = $(v).val().match(/^(\d{1,4})$/);
						if(typeof judgeTableDate == 'function')judgeTableDate(v,formatDate(new Date(r[1]),'year'),elemtr,datafield);
						else{
							$(v).val(formatDate(new Date(r[1]),'year'));
							listData[elemtr][datafield] = formatDate(new Date(r[1]),'year');
						}
					}else errorMsg = '请输入正确时间格式，形如2020';
					break;
				case 't_monthly':
					if(judgeStrYear($('#'+v.fields).val())){//验证年份格式
						// var r = $('#'+v.fields).val().match(/^(\d{1,4})(-|\/|.)(\d{1,2})$/);
						if(typeof judgeTopDate == 'function'){
							judgeTopDate('#'+v.fields,formatDate(new Date(r[1]),'month'));
						}else $('#'+v.fields).val(formatDate(new Date(r[1]),'month'));
					}else errorMsg = '请输入正确时间格式，形如2022-01';
					break;
			}
			if(errorMsg){//如果存在错误提示，则清空控件内容并提示错误
				$(v).val('');
				listData[elemtr][datafield] = '';
				layer.msg(errorMsg);
			}
		})
		laydate.render({
			elem: $(v).next()[0],//为图标绑定事件
			type: $(v).attr('fft').split('_')[1],
			trigger: 'click',
//			showBottom: false,//显示底部栏会出现控件闪现的问题
			calendar: true,//显示公历节日
			done: function (value, date) {
				if(typeof judgeTableDate == 'function')judgeTableDate(v,value,elemtr,datafield);//存在日期判断则执行
				else{
					$(v).val(value);//原输入控件赋值
					listData[elemtr][datafield] = value;
				}
			}
		});
	});
	if(typeof dropDownEditList != 'undefined'){//下拉可编辑控件
		$.each(dropDownEditList,function(i,v){
			if(v == 'fXsFpsl' || v =='fCgFpSl')changeFpslInTable(v,listData);
			else changeDropdownInTable(v,listData);
		});
	}
	$.each(fieldFrontEditList,function(i,v){//表格不可编辑字段设置背景色
		if(isChild)$($('.layui-table-view')[1]).find(".layui-table-main [data-field='"+v+"']").css('background-color','#F2F2F2');
		else $($('.layui-table-view')[0]).find(".layui-table-main [data-field='"+v+"']").css('background-color','#F2F2F2');
	});
	if(typeof tableSpecialDone== 'function')tableSpecialDone(listData);//如果单据存在需要特殊处理的表格回调方法则执行
}
/*
 * table导入execl
 * param：obj input对象
 * param：tableId 表格ID标识
 * param：importFields 对应导入字段
 * param：listData 表缓存
 * param：moduleTable 模块名称
 * param：decimalObj 表格数据类型字段名及小数位
*FileReader共有4种读取方法：
*1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
*2.readAsBinaryString(file)：将文件读取为二进制字符串
*3.readAsDataURL(file)：将文件读取为Data URL
*4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
*/
function importExcel(obj, tableId, importFields, listData, moduleTable, decimalObj) {
	var wb;//读取完成的数据
	var rABS = false; //是否将文件读取为二进制字符串
	var iid;
	if(!!listData.length)iid=Number(listData[listData.length-1]['iid']);else iid=1;
	if(!obj.files) {
		return;
	}
	const IMPORTFILE_MAXSIZE = 1*2048;       //这里可以自定义控制导入文件大小
	var suffix = obj.files[0].name.split(".").slice(-1);
	if(suffix != 'xls' && suffix !='xlsx'){
		layer.msg('导入的文件格式不正确!')
		return
	}
	if(obj.files[0].size/1024 > IMPORTFILE_MAXSIZE){
		layer.msg('导入的表格文件不能大于2M')
		return
	}
	var f = obj.files[0];
	var reader = new FileReader();
	reader.onload = function(e) {
		var data = e.target.result;
		if(rABS) {
			wb = XLSX.read(btoa(fixdata(data)), {     //手动转化
				type: 'base64'
			});
		} else {
			wb = XLSX.read(data, {
				type: 'binary',
				cellDates: true,  //把时间格式数据格式化
				dateNF: 'yyyy-MM-dd'
			});
		}
		var strForm=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
		for(var i=0; i<strForm.length; i++){
			var trData = {};
			$.each(gridColumns.gridNewLine,function(gi,gv){trData[gi]=gv;})//逐个添加，防止污染新增模板
			trData['iid'] = listData.length?(Number(listData.slice(-1)[0]['iid'])+1):1;
			$.each(importFields,function(j,v){//填充存在的数值,导入字段部分带必填*,导入模板可能不带
				var hasValue = strForm[i][j.replace("*", "")] || strForm[i][j];
				trData[v] = hasValue ? hasValue.replace(/(^\s*)|(\s*$)/g, "").replace(/[\r\n]/g, "") : '';//导入模板必填字段存在‘*’,并去除两端空格以及回车
				if(typeof decimalObj !== 'undefined' && v in decimalObj)trData[v] = trData[v].replace(',','');//数值类型去除千分位的'，'
				if(v.indexOf("d") == 0){//字段名d开头为日期字段，需替换符号
					trData[v] = trData[v].replace(/\//g,"-");
				}
			})
			if(['TP_STOCKOFFERPRICE','TP_STOCKBARGAININ','TP_STOCKBARGAININDETAIL'].includes(moduleTable)){//销售报价、销售合同、合同清单新增
				trData.gIDC = trData.gIDC || trData.gID;//客户型号
				trData.gNameC = trData.gNameC || trData.gName;//客户品名
				trData.vWlBhC = trData.vWlBhC || trData.vWlBh;//客户物料编号
				trData['bPrice'] = trData['bPrice'] ? Number(trData['bPrice']).toFixed(decimalObj.bPrice) : 0;
				trData['bNumb'] = trData['bNumb'] ? Number(trData['bNumb']).toFixed(decimalObj.bNumb) : 0;
			}
			listData.push(trData);
		}
		listData = calcDetail(listData);//导入数据资金计算
		table.reload(tableId,{data:listData});
	};
	if(rABS) {
		reader.readAsArrayBuffer(f);
	} else {
		reader.readAsBinaryString(f);
	}

	return true;
}
/*
 * 获取表格数据
 * param：url 数据源
 * param：dataStr 数据存放对象
 * */
function getTableData(url, dataStr){
	$.get(url,function(data){
		if(data.count > 0){
			for(var i=0;i<data.data.length;i++){
				dataStr.push(data.data[i])
			}
		}
	});
}
/*
 * 表格select下拉赋值
 * param：obj 操作对象
 * param：fieldName 字段名
 * param：isChild 是否子表
 * */
function tableSelected(obj, fieldName,isChild=false){
	var selectIndex=obj.tr[0].rowIndex;
	form.on('select(select_table)', function (obj) {//监听下拉框
		var value = obj.value;	//选中的值
		if(isChild){//是否子表
			$.each(table.cache.dhtable1,function(i,v){
				v.LAY_TABLE_INDEX = i;//排序后LAY_TABLE_INDEX被清除，重新按顺序赋值
				if(v.LAY_TABLE_INDEX==selectIndex){//缓存表内的下标和当前事件行下标的判断
					v[fieldName]=value;
				}
			});
		}else{
			$.each(table.cache.dhtable,function(i,v){
				v.LAY_TABLE_INDEX = i;//排序后LAY_TABLE_INDEX被清除，重新按顺序赋值
				if(v.LAY_TABLE_INDEX==selectIndex){//缓存表内的下标和当前事件行下标的判断
					v[fieldName]=value;
				}
			});
		}
	});
}
/*
 * 表格批量删除行
 * param：tableId 表格ID标识
 * param：listData 表缓存
 * param：checkStatus 表格选中行对象
 * */
function tableDeleteBatch(tableId, listData, checkStatus){
	if(checkStatus.data.length == 0){
		layer.msg("请先选择明细！");
	}else{
		$.modal.confirmCom('确定要删除么？',function(result){
			for(var i=listData.length-1; i>=0; i--){
				if(listData[i]["LAY_CHECKED"]){
					listData.splice(i, 1);    //删除一项
				}
			}
			layer.closeAll();
			table.reload(tableId, {data : listData});
		});
	}
}
/*
 * 单据表头按钮操作
 * param：btnname 按钮标识
 * param：beforeSaveFlag 提交之前的数据验证
 * param：tableData 明细表缓存
 * */
function tpBtnClick(btnname,beforeSaveFlag=true){
	var tabTitleObj = $('.layui-tab-title', parent.document).find('.layui-this').find('span');//当前tab对象
	var tabName = tabTitleObj.html();
	switch(btnname){
		case 'tpPrev'://前单
		case 'tpNext'://后单
			if(btnname == 'tpPrev')var getDataUrl = moduleUrl+'/lastnid?flowtype=last&nid='+nid;
			else var getDataUrl = moduleUrl+'/nextnid?flowtype=next&nid='+nid;
			$.operate.get(getDataUrl, function(res){
				if(res.code == 0){
					res.data = JSON.parse(res.data);
					tabName = tabName.replace($("#bid").val(),res.data.bid);
					tabName = tabName.replace(' - 新增','('+res.data.bid+')');
					tabTitleObj.html(tabName);
					tabTitleObj.parent().attr('lay-id',tabTitleObj.parent().attr('lay-attr') + '?nid=' + res.data.nid);//动态修改标签页layid，防止切换前单后在查询列表进入错误
					window.location.href = moduleUrl+'/edit?nid='+res.data.nid;
				}
			})
			break;
		case 'tpSearch'://查询
			parent.layui.index.openTabsPage(moduleUrl, tabName.replace(' - 新增',' - 查询').replace('('+$("#bid").val()+')',' - 查询'));
			break;
		case 'tpAdd'://单据新增
			if(moduleTable == 'TP_FBAPLANORDER'){
				if ($('#isDeliver').val() == 1){
					tabName = '头程计划单 - 海外仓发货';
				}  else {
					tabName = '头程计划单 - 新增';
				}
				tabTitleObj.html(tabName);
				tabTitleObj.parent().attr('lay-id',tabTitleObj.parent().attr('lay-attr') + '?nid=0');//动态修改标签页layid，防止切换前单后在查询列表进入错误
				goUrl(moduleUrl+'/edit?nid=0'+ '&isDeliver='+$('#isDeliver').val());
			}else {
				if(tabName.substring(tabName.length-2,tabName.length)!='新增')tabName=tabName.split('(')[0]+' - 新增';
				tabTitleObj.html(tabName);
				tabTitleObj.parent().attr('lay-id',tabTitleObj.parent().attr('lay-attr') + '?nid=0');//动态修改标签页layid，防止切换前单后在查询列表进入错误
				goUrl(moduleUrl+'/edit?nid=0');
			}
			break;
		case 'tpSave'://单据保存
			var tableData=(typeof table=='undefined')?(noTable.length>0?noTable:[{'nid':0}]):table.cache.dhtable;//没有定义table以及为制单状态时
			if(tableNoMust)tableData = [{'nid':0}];
			var is_return = 0,//是否中断保存
				judge_fields=k_fields.concat(t_fields),//判断必填字段：静态表格(表头加静态网格字段)
				must_field={},//表头必填且不隐藏字段
				inputForm = $(".head-form");//单据表头表单
//	        $.each(b_fields,function(k,v){//特殊处理：页脚隐藏字段的数值类型
//	        	if(v.fieldType=='decimal(19,6)')headData[v.fields]=Number(headData[v.fields]);
//	        });
//			if(typeof table=='undefined')judge_fields=k_fields.concat(t_fields);//判断必填字段：静态表格(表头加静态网格字段)
//			else judge_fields=k_fields;
			$.each(judge_fields,function (fk,fv) {
				if(moduleTable == 'TCRM_BUSINESSINFO' && $("#"+fv.fields+"_div").css('display') === 'none'){return true;}//商机信息存在前端切换商机类型隐藏，需特殊处理过滤必填字段
				// if(fv.fieldFrontRequired && !fv.fieldFrontHidden)must_field[fv.fields] = fv.fieldName + " 不能为空";//遍历必填且不隐藏的字段
				if(fv.fieldFrontRequired)must_field[fv.fields] = fv.fieldName + " 不能为空";//遍历必填且不隐藏的字段
			})
			$.each(must_field,function (k,v) {
				if(!inputForm.find("[name='"+k+"']").val()){
					$.modal.msgError(v);
					is_return = 1;
					if(!typeof table=='undefined')inputForm.find("#"+k).css('border','1px solid red');
					inputForm.find("#"+k).focus();
					return false;
				}
			})
			if(is_return)return false;
			console.log(tableData,999)
			if(tableData.length == 0 && nid == 0 && !tableNoMust){//表格必填并且没有明细且为新增状态
				layer.msg('单据明细 不能为空');
				is_return = 1;
			}
			if(is_return)return false;
			if(tableData.length > 0 && !tableNoMust){//判断明细必填
				$.each(tableData, function(ti, tv){
					$.each(tableData,function(tii,tvv){
						if(ti != tii && tv['iid'] && tvv['iid'] && tv['iid'] == tvv['iid']){
							layer.msg('明细第 '+ (ti+1) +' 行与第 '+ (tii+1) +' 行【行号】重复！');
							is_return = 1;
							return false;
						}
						if(is_return)return false;
					})
					if(is_return)return false;
					$.each(gridColumns.fieldRequiredList, function(tmi, tmv){
						if(!tv[tmv] && tv[tmv] !== 0){//为0亦可保存
							layer.msg('明细第 '+ (ti+1) +' 行 '+gridColumns.fieldNameRequiredList[tmi]+' 不能为空');
							is_return = 1;
							return false;
						}
						if(is_return)return false;
					});
					if(is_return)return false;
				});
			}
			if(is_return)return false;
			if(beforeSaveFlag && typeof beforeSave=='function')tableData=beforeSave(tableData);//判断该页面是否有点击保存之前的函数
			if(typeof tableData == 'boolean' && !tableData)return false;//如果beforeSave返回的表数据为false，则终止保存
			if(typeof tableData=="string"){//如果beforeSave返回的表数据为字符串，则终止保存并提示错误语句
				$.modal.msgError(tableData);
				return false;
			}
			var headData=inputForm.serializeFormToJson();
			$.each(k_fields,function(i,v){//单据表头的复选框没有选中时无法获取到false,且选中赋值为字符串'1'
				if(v.fieldFrontType == 't_checkbox'){
					if($('#'+v.fields).prop('checked'))headData[v.fields]=true;
					else headData[v.fields]=false;
				}
			})
			//【品牌、型号、规格、品名、系列、单位】去除前后空格回车
			var filterBlankArr = ['gBrand','gID','gModel','gName','gSerial','gUnit'];
			$.each(filterBlankArr,function(i,v){
				if(headData[v])headData[v] = headData[v].replace(/(^\s*)|(\s*$)/g, "").replace(/[\r\n]/g, "");
				$.each(tableData,function(ii,vv){
					if(vv[v])vv[v] = vv[v].replace(/(^\s*)|(\s*$)/g, "").replace(/[\r\n]/g, "");
				})
			})
			var postData = {'infoMap':JSON.stringify(headData),'infoItems':JSON.stringify(tableData)};//转化为json字符串格式
			$.operate.post(moduleUrl+'/editpost', postData, function(res){
				if(res.code == 0){
					if(nid==0)$.operate.get(moduleUrl+'/lastnid?nid=0', function(res2){//当为新增单据时，获取新增保存单据的bid，改变标题
						if(res2.code == 0){
							res2.data = JSON.parse(res2.data);
							tabName = tabName.replace(' - 新增','('+res2.data.bid+')');
							tabTitleObj.html(tabName);
							if(typeof afterSave=='function')afterSave(res2);//单据保存后的操作
						}
					})
					else if(typeof afterSave=='function')afterSave(res);//单据保存后的操作
					if(typeof table=='object' && !tableNoMust && table.cache.dhtable.length==0 ){//存在数据表格且表缓存无数据时表格删除单据时
						tabName=tabName.split('(')[0]+' - 新增';
						tabTitleObj.html(tabName);
					}
					$.cookie('dhecp_tpTransfer', 1, { expires: 1, path: '/' });//保存成功后存放流转cookie
					goUrl(moduleUrl+'/edit?nid='+res.data);
				}
			});
			break;
		case 'sgzzadd':
			var headData=$(".head-form").serializeFormToJson();
            var isxd=true
            $('.tbody').each(function (i,s) {
				var addnum = 0
				var a = 0
				$(this).children('tr').each(function (v) {
					if ($(this).children('.ftotalDemand').text()){
						if(a!=addnum){
							isxd=false
						}
						a=$(this).children('.ftotalDemand').text()
						addnum = 0
					}
					addnum=addnum+(+$(this).children().children('.quantityRequired').val())
				})
				if(a!=addnum){
					isxd=false
				}
				console.log('1a',a)
				console.log("1addnum",addnum)
                // var a=$('.ftotalDemand').text()
                // var addnum=0
                // $(this).children('tr').each(function (v) {
				// 	addnum = addnum+(+$(this).children().children('.quantityRequired').val())
                // })
				// if(a!=addnum)isxd=false

                // if(a!=addnum)isxd=false
            })
			
            if(!isxd)return layer.msg('需求数量不符')
            var is_return = false//是否中断保存

            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                    if(!$('#'+v.fields).val()){
                         layer.msg(v.fieldName+'不能为空')
                         is_return=true
                    }
                }
            })
            if(is_return) return;
            var daraArr=[]
		    var isjx=true
		    var isxq=true


		    $('.tbody tr').each(function (i) {
		    	let obj={}
		    	obj.guid=$(this).children('.guid').val()
		    	obj.sCode=$(this).children('.sCode').val()
		    	obj.sName=$(this).children('.sName').val()
		    	obj.sNum=$(this).children('.sNum').val()
		    	obj.totalDemand=$(this).children('.totalDemand').val()
		    	obj.sBz=$(this).children('.sBz').val()
		    	obj.goodsAllocation=$(this).children('.goodsAllocation').text()
		    	obj.goodsArea=$(this).children('.goodsArea').text()
		    	obj.warehouseAddress=$(this).children('.warehouseAddress').text()
		    	obj.stockNum=$(this).children('.stockNum').text()
		    	obj.quantityRequired=$(this).children().children('.quantityRequired').val()

		    	obj.vGsMc=$(this).children('.vGsMc').val()
		    	obj.vGsJc=$(this).children('.vGsJc').val()
		    	obj.vGsBm=$(this).children('.vGsBm').val()
		    	obj.rkGuid=$(this).children('.rkGuid').val()
		    	obj.rkBid=$(this).children('.rkBid').val()
		    	obj.vHw=$(this).children('.vHw').val()
		    	obj.vKq=$(this).children('.vKq').val()
		    	obj.gDepot=$(this).children('.gDepot').val()
		    	if(!obj.quantityRequired)isjx=false
				if(obj.quantityRequired*1 > obj.stockNum*1)isxq=false
		    	daraArr.push(obj)
			})
		    if(!isjx)return layer.msg('请填写需求数量')
		    if(!isxq)return layer.msg('需求数量不可超过库存数量')
            $.operate.post("/storage/manualassembly/editpost",{'infoMap':JSON.stringify(headData),infoItems:JSON.stringify(daraArr)},function(res){
                layer.msg(res.msg)
                if(res.code==0){
                    nid = res.data
                    console.log("nid",nid)
                    setTimeout(function(){
                        window.location.href="/storage/manualassembly/edit?nid="+nid;
                    }, 1000);
                }
            })
		    break;
		case 'tpTransfer'://流转
		case 'tpReturn'://退回
		case 'tpReject'://驳回
			if($(activeFlow).val()=='end'){
				layer.alert('单据流程已结束，不能再次操作', {icon: 7,title: "系统提示"});
				return;
			}
			var headData = $(".head-form").serializeFormToJson(),title,toUrl;
			var infoMap = JSON.stringify(headData);
			if (beforeSaveFlag && typeof beforeFlow == 'function') headData = beforeFlow(headData, btnname); //判断该页面是否有点击流程改变之前的函数
			if (typeof headData == 'boolean' && !headData) return false; //如果beforeSave返回的表数据为false，则终止保存
			if (typeof headData == "string") { //如果beforeSave返回的表数据为字符串，则终止保存并提示错误语句
				$.modal.msgError(headData);
				return false;
			}
			if(btnname == 'tpTransfer'){
				toUrl = moduleUrl+'/flowpage?fType=flow_go';
				title='流转页面';
			}else if(btnname == 'tpReturn'){
				toUrl = moduleUrl+'/flowpage?fType=flow_back';
				title='退回页面';
			}else if(btnname == 'tpReject'){
				toUrl = moduleUrl+'/flowpage?fType=flow_reject';
				title='驳回页面';
			}
			$.post(toUrl, {
				'infoMap': infoMap
			}, function (res) {
				console.log(res);
				if (res.code == 0) {
					var mwidth = ($(window).width() - 100 > 800) ? 800 : ($(window).width() - 100),
						mheight = ($(window).height() - 100 > 700) ? 700 : ($(window).height() - 100);
					$.modal.open(title, res.data, mwidth, mheight, function (index) {
						var result = window["layui-layer-iframe" + index].processTaskCallback();
						if (result) {
							$('.layui-layer-btn0').attr('style', 'display:none'); //隐藏确定按钮
							result.data['infoMap'] = infoMap; //为流转添加infoMap参数
							$.operate.save(result.url, result.data, function (res2) {
								if (res2.code == 0) {
									$.modal.closeLoading();
									layer.closeAll();
									layer.msg(res2.msg, {
										icon: 1
									});
									top.refreshTask(); //刷新任务数量
									setTimeout(function () {
										window.location.reload();
									}, 1000);
								} else {
									layer.closeAll();
									$.modal.msgError(((res2 == undefined) ? "操作错误！" : res2.msg), modal_status.FAIL);
								}
							});
						}
					});
				} else $.operate.ajaxSuccess(res);
			})
			break;
		case 'tpReset': //重置
			var toUrl = moduleUrl + '/flowbackpost';
			if (nid == 0) {
				$.modal.msgError('制单环节不需要重置！', icon = 2);
			} else {
				$.modal.confirmCom('是否将单据重置到初始状态？', function () {
					layer.closeAll();
					$.operate.post(toUrl, {'tableDataId': nid,'optType': 'reset'}, function (res) {
						if (res.code == 0) setTimeout(function () {window.location.reload();}, 1000);
					})
				});
			}
			break;
		case 'tpDelete': //删除
			if (nid == 0) {
				$.modal.msgError('新增单据无需删除！', {icon: 2});
			} else {
				$.modal.confirmCom('是否删除该单据？', function () {
					layer.closeAll();
					var postData = {'infoMap': JSON.stringify($(".head-form").serializeFormToJson()),'infoItems': JSON.stringify([])};
					if (typeof beforeDelete == 'function') postData = beforeDelete(postData); //判断该页面是否有点击保存之前的函数
					$.operate.post(moduleUrl + '/editpost', postData, function (res) {
						if (res.code == 0) {
							if (moduleTable == 'TP_FBAPLANORDER'){
								if ($('#isDeliver').val() == 0){
									tabName = tabName.split('(')[0] + ' - 新增';
									tabTitleObj.html(tabName);
									goUrl(moduleUrl + '/edit?nid=' + res.data+ '&isDeliver='+$('#isDeliver').val());
								} else {
									tabName = tabName.split('(')[0] + ' - 海外仓发货';
									tabTitleObj.html(tabName);
									goUrl(moduleUrl + '/edit?nid=' + res.data + '&isDeliver='+$('#isDeliver').val());
								}

							} else {
								tabName = tabName.split('(')[0] + ' - 新增';
								tabTitleObj.html(tabName);
								goUrl(moduleUrl + '/edit?nid=' + res.data);
							}
						}
					});
				});
			}
			break;
		case 'tpExport'://导出——单个单据
			if(nid==0){
				$.modal.msgError('单据未保存无法导出！',{icon:2});
			}else{
				$.ajax({
					url: moduleUrl+"/export?nodatascode=1&nid="+nid,
					data: typeof specifiedExportFields == 'string' && specifiedExportFields!=''?{'specifiedExportFields':specifiedExportFields}:{},
					type: 'GET',
					dataType: 'json',
					beforeSend: function(){
						showloadings(true);
					},
					success: function(result){
						if (result.code == 0) {
							window.open(ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true, "_blank");
//					        window.location.href = ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true;
//					        parent.$('.page-loading').hide();//页面进行了跳转刷新，需要手动关闭页面的加载动画
						} else if (result.code == web_status.WARNING) {
							$.modal.alertWarning(result.msg)
						} else {
							$.modal.alertError(result.msg);
						}
						showloadings(false);
					}
				});
			}
			break;
		default:
			$.modal.msgError('该按钮未设置动作！',{icon:7});
			break;
	}
}
/*
 * 验证表格编辑并返回固定小数位数
 * param：editObj 当前编辑对象值、字段名、所在行的所有相关数据  
 * param：decimalObj 表格数据类型字段名及小数位
 * */
function checkEdit(editObj, decimalObj){
	var decimalNum = decimalObj[editObj.field];
	if(decimalNum > -1){
		if((moduleTable=='TP_STOCKBARGAININCHANGE' && $.common.isNumber(editObj.value,true)) ||$.common.isNumber(editObj.value)){//销售合同修改可填负值
			return Number(editObj.value).toFixed(decimalNum);//toFixed返回string类型，'0'亦是true
		}else{
			layer.msg('请填写正确数值！')
			return false;
		}
	}
}
/*
 * 验证表格编辑
 * param：editObj 当前编辑对象值、字段名、所在行的所有相关数据  
 * param：decimalObj 表格数据类型字段名及小数位
 * */
function getDecimalNum(fields, decimalObj){
	var decimalNum = decimalObj[fields];
	if(decimalNum > -1){
		return decimalNum;
	}else{
		return false;
	}
}
/*
 * 通过dom给表格内控件渲染值
 * param：layID 表格ID标识
 * param：dataIndex 行号
 * param：dataField 字段名
 * param：data 赋值
 * */
function setTableValue(layID, dataIndex, dataField, data){
	var tdHtml=$("[lay-id="+layID+"]").find("[data-index="+dataIndex+"]").find("[data-field="+dataField+"]");
	if(tdHtml.length!=0){
		if(tdHtml.find('input').length==0){
			if(tdHtml.find('span').length==0)tdHtml.children().html(data);//普通可编辑table单元格
			else tdHtml.find('span').html(data);//不可编辑弹出框或文本域
		}else tdHtml.find('input').val(data);//可编辑弹出框
	}
}
/*
 * 调入数据处理
 * param：obj 调入对象
 * */
function relationIn(obj){
	var did='dhtable',
		tcd=(typeof table == 'object')?table.cache.dhtable:null,
		ld=listData,gc=gridColumns;
	if($(obj).attr('moduleTable')){//判断是否从表的调入
		did='dhtable1';
		tcd=(typeof table == 'object')?table.cache.dhtable1:null;
		ld=listData1;
		gc=gridColumnsOn;
	}
	$.modal.open(obj.text, "/common/relation/relationpage?relationguid="+obj.getAttribute('value'),$(window).width()-200,$(window).height()-100, function(index){
		var res = window["layui-layer-iframe" + index].callbackdata();
		console.log(res);
		if(res.dataStr.length==0){
			layer.msg("无数据，请选择！",{icon:7});
		}else{
			var flag=true,copyHead;
			if(tcd){
				$.each(res.bFieldKeys,function(k,v){//主键列判断调入数据是否重复
					$.each(tcd,function(k2,v2){
						$.each(res.dataStr,function(k3,v3){
							if(v3[k]==v2[v])flag=false;
						});
					});
				});
			}
			if(flag){
				var differentHF=[];
				$.each(res.headFields,function(k,v){//调入数据的单据表头字段判断重复
					$.each(res.dataStr,function(k2,v2){
						if(k2!=0 && res.dataStr[0][v]!=v2[v]){
							if(!differentHF.includes(res.headFieldNames[v]))differentHF.push(res.headFieldNames[v]);
							flag=false;
						}
					});
				});
				if(flag){
					$.each(res.headFields,function(k,v){//调入数据和单据表头字段要求相同(明细存在数据的情况下)
						$.each(res.dataStr,function(k2,v2){
							if(typeof table == 'object' && !!table.cache.dhtable.length && $('#'+k).val() && $('#'+k).val()!=v2[v]){
								if(!differentHF.includes(res.headFieldNames[v]))differentHF.push(res.headFieldNames[v]);
								flag=false;
							}
						});
					});
					if(flag){
						$.each(res.dataStr,function(i,v){//根据 decimalObj限制小数位数
							$.each(v,function(j,k){
								if(decimalObj[j]>-1 && k)v[j]=Number(k).toFixed(decimalObj[j]);//存在值并且decimalObj存在该属性才限制小数位，否则空值会赋值0
							})
						})
						$.each(res.headFields,function(k,v){//表头赋值
							$('#'+k).val(res.dataStr[0][v]);
						})
						if(Object.keys(res.gridFields).length > 0 && typeof table == 'object'){
							var newListData=[];
							$.each(res.dataStr,function(k,v){
								var newData={};//不能直接赋值到newData，只能一个个属性添加，否则会污染新增模板
								$.each(gc.gridNewLine,function(k3,v3){newData[k3]=v3;});//基础新增行模板
								$.each(res.gridFields,function(k2,v2){//新增数据
									if(v[v2] != null && v[v2] !== "")newData[k2]=v[v2];//防止赋空值(只判断null和空字符串，0还是要赋值)
								});
								if(!!ld.length)newData['iid']=Number(ld[ld.length-1]['iid'])+k+1;else newData['iid']=1+k;//iid赋值
								newListData.push(newData);
							})
							ld.push.apply(ld,newListData);
							table.reload(did, {data : ld});
						}
						if(moduleTable=='TP_PRODUCTMG') funChild();
						layer.close(index);
						form.render();//渲染下拉框
						if(typeof relationAfter== 'function')relationAfter(res);//调入赋值回调
					}else{
						layer.msg("调入数据与单据表头数据冲突！<br/>错误字段："+Object.values(differentHF),{icon:7});
					}
				}else{
					layer.msg("表头数据不唯一！请重新选择！<br/>错误字段："+Object.values(differentHF),{icon:7});
				}
			}else{
				layer.msg('单据中已有相同明细，请重新选择！',{icon:7});
			}
		}
	});
}
//导入、匹配产品资金重计算
function calcDetail(rowData){
	var sl=$("#fCgFpSl").val()?$("#fCgFpSl").val():$("#fXsFpsl").val(),//优先取表头的税率(优先采购税率)
		dj=useHs?'bPrice':'fWsDj',
		mj=useHs?'fHsMj':'fWsMj';//根据全局系统设置，以含税、未税面价进行单价与折扣互算
	if(sl)sl=Number(sl);
	else sl=0;
	for(var i = 0; i < rowData.length; i++){
		if(!sl)sl=rowData[i]['fCgFpSl']?rowData[i]['fCgFpSl']:(rowData[i]['fXsFpsl']?rowData[i]['fXsFpsl']:null);//表头没有税率则取明细的税率
		rowData[i]['fSumje'] = (Number(rowData[i]['bNumb']?rowData[i]['bNumb']:0)*Number(rowData[i]['bPrice']?rowData[i]['bPrice']:0)).toFixed(decimalObj.fSumje);
		rowData[i]['fWsDj'] = (Number(rowData[i]['bPrice']?rowData[i]['bPrice']:0)/(1 + sl/100)).toFixed(decimalObj.fWsDj);
		rowData[i]['fWsJe'] = (Number(rowData[i]['fSumje'])/(1 + sl/100)).toFixed(decimalObj.fWsJe);
		rowData[i]['fSe'] = (Number(rowData[i]['fSumje'])-Number(rowData[i]['fWsJe'])).toFixed(decimalObj.fSe);
		if(rowData[i]['bPrice']!=null && rowData[i]['gPrice']!=null && rowData[i]['bNumb']!=null){//存在单价、成本价、数量时==>计算单项毛利
			rowData[i]['fDxMl'] = Number(rowData[i]['bNumb'] * (rowData[i]['bPrice'] - rowData[i]['gPrice'])).toFixed(decimalObj.fDxMl);
		}
		rowData[i]['fBjzk'] = (Number(rowData[i][mj])?Number(rowData[i][dj])/Number(rowData[i][mj]):0).toFixed(decimalObj.fBjzk);
		rowData[i]['fHtzk'] = (Number(rowData[i][mj])?Number(rowData[i][dj])/Number(rowData[i][mj]):0).toFixed(decimalObj.fHtzk);
		rowData[i]['fCgZk'] = (Number(rowData[i][mj])?Number(rowData[i][dj])/Number(rowData[i][mj]):0).toFixed(decimalObj.fCgZk);
	}
	return rowData;
}
//行event事件监听
function toolEvent(ftable){
	table.on('tool('+ftable+')', function(obj){
		if(obj.event.indexOf('select_')==0)tableSelected(obj, obj.event.split('_')[1]);//表格select下拉赋值，下拉框事件赋予赋值动作
	});
	form.on('switch(switchTable)', function(obj){//监听开关动作
		var cChecked=obj.elem.checked?true:false,cIndex=$(this).attr('tindex'),cName=$(this).attr('tname');
		table.cache.dhtable[cIndex][cName]=cChecked;
	});
}
//通用表格头部工具栏事件监听
function toolbarEvent(){
	table.on('toolbar(ftable)', function(obj){
		var checkStatus = table.checkStatus('dhtable');
		switch(obj.event){
			case 'addBtn'://新增明细
				if(listData.length > 0){
					if(listData[listData.length - 1]['iid']){
						gridColumns.gridNewLine.iid = Number(listData[listData.length - 1]['iid']) + 1;//行号自增1
					}else{
						gridColumns.gridNewLine.iid = 1;
					}
				}else{
					gridColumns.gridNewLine.iid = 1;
				}
				if (moduleTable == 'TCW_OPERATEEXPENSETRANSFERTC'){
					gridColumns.gridNewLine.vJyLx = '物流服务→头程运费'
				}
				listData.push(gridColumns.gridNewLine);
				table.reload('dhtable', {data : listData});
				form.render();
				break;
			case 'deleteBatch'://删除明细
				tableDeleteBatch('dhtable', listData, checkStatus);
				break;
			case 'calluser'://调入员工
			    var selectedObject=""
                sessionStorage.setItem('tabledata',JSON.stringify(table.cache.dhtable))
                table.cache.dhtable.map((v,i)=>{
                    if(selectedObject){
                        selectedObject+=','+v.gUser
                    }else{
                        selectedObject+=v.gUser
                    }
                })
			    layer.open({
                	type: 2,
                	area: [($(window).width() - 400)+'px', ($(window).height() - 200)+'px'],
                	fix: false,//不固定
                	offset: '5%',//距离顶部
                	maxmin: true,//最大最小化
                	shade: 0.3,//遮罩
                	title: '调入员工',
                	content: "/system/user/userselect?pagetype=checkbox&by=direct&fmoduleTable="+moduleTable+"&selectedUser="+selectedObject,
                	btn: ['确定', '取消'],
                	shadeClose: true,// 弹层外区域关闭
                	yes: function(index, layero){
						var res  = window["layui-layer-iframe" + index].callbackdata();
				        if(res.length > 0){
							layer.closeAll();
						   var tabledata=sessionStorage.getItem('tabledata')
                            if(tabledata){
                                tabledata=JSON.parse(tabledata)
                                let newall=[]
                                let endData = [];
                                for (let i = 0; i < res.length; i++) {
									res[i].gUser=res[i].userId
						            res[i].gUserName=res[i].userName
						            res[i].gDeptName=res[i].deptName
						            res[i].vGw=res[i].positionNameDa
                                    var isdata=false
                                    if (newall.indexOf(res[i].gUser) === -1) {
                                        for (let n = 0; n < tabledata.length; n++) {
                                            if (newall.indexOf(res[i].gUser) === -1) {
                                                if(res[i].gUser==tabledata[n].gUser){
                                                   isdata=true
                                                   endData.push(tabledata[n]);
                                                   newall.push(tabledata[n].gUser);
                                                }
                                            }
                                        }
                                        if(!isdata){
                                            endData.push(res[i]);
                                            newall.push(res[i].gUser);
                                        }
                                    }
                                }
								endData.map((v,i)=>{v.iid=i})
                                table.reload('dhtable', {data:endData});
                            }else{
								res.map((v,i)=>{v.iid=i})
                                table.reload('dhtable', {data:res});
                            }
				        }else{
                            layer.msg("请选择数据");
                        }
                	}
                });
				break;
			case 'copyBtn'://复制明细
				if(checkStatus.data.length == 0){
					layer.msg("请先选择数据！");
				}else{
					$.each(checkStatus.data,function(i,v){
						delete v.guid;//防止插入重复键
						v.iid = Number(listData[listData.length-1].iid) + i + 1;//累加行号
					})
					listData = listData.concat(checkStatus.data);
					table.reload('dhtable', {data : listData});
				}
				break;
			case 'fieldSet'://列设置
				filedSet(moduleTable+'_EditPage202109');
				break;
			case 'tableFull'://表格展开
				$('.north .layui-form').hide();
				table.reload('dhtable',{
					defaultToolbar: [{title:'收缩',layEvent:'tableShrink',icon:'layui-icon-screen-restore'}],
					height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
				});
				break;
			case 'tableShrink'://表格收缩
				$('.north .layui-form').show();
				table.reload('dhtable',{
					defaultToolbar: [{title:'展开',layEvent:'tableFull',icon:'layui-icon-screen-full'}],
					height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
				});
				break;
			case 'importBtn'://导入
				$.tablelist.importExcel('dhtable',importFields, table.cache.dhtable, moduleTable, decimalObj);
				break;
			case 'exportTab'://导出表格
				var pd = {};
				if(typeof specifiedExportFields == 'string' && specifiedExportFields!='')pd.specifiedExportFields = JSON.stringify(specifiedExportFields);
				pd.dataList = JSON.stringify(table.cache.dhtable);
				pd.getFieldAttributesType = 'template';
				$.ajax({
					url: moduleUrl+"/export",
					data: pd,
					type: 'post',
					dataType: 'json',
					beforeSend: function(){
						showloadings(true);
					},
					success: function(result){
						if (result.code == 0) {
							window.open(ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true, "_blank");
						} else if (result.code == web_status.WARNING) {
							$.modal.alertWarning(result.msg)
						} else {
							$.modal.alertError(result.msg);
						}
						showloadings(false);
					}
				});
				break;
			case 'model'://导入型号
				layer.open({
					type: 1,
					offset: '20%',
					title: '导入型号（每个型号以回车换行区分）',
					shade: 0.3,//遮罩
					shadeClose: true,// 弹层外区域关闭
					area: ['400px', '350px'],
					content: '<textarea id="textareaVal" style="width:398px;height:240px;background:#e2eff9"></textarea>',
					btn: ['确定', '取消'],
					yes: function(index, layero){
						var textareaVal = $("#textareaVal").val();
						$.each(textareaVal.split('\n'),function(i,v){
							var newData={};//不能直接使用gridColumns.gridNewLine,会破坏原始新增行模板,并且需要重新new
							$.each(gridColumns.gridNewLine,function(k,j){newData[k]=j;});//基础新增行模板
							if(!!listData.length)newData['iid']=Number(listData[listData.length-1]['iid'])+1;else newData['iid']=1;//iid赋值
							newData['gID']=v;
							listData.push(newData);
						})
						table.reload('dhtable', {data : listData});
						layer.close(index);
					}
				});
				break;
			case 'matching'://匹配产品
				var postData=listData,relationguid;
				$.each($('.layui-nav dl dd a'),function(i,v){
					if($(v).text().indexOf("产品信息")>-1)relationguid=$(v).attr('value');
				})
				$.each(postData,function(i,v){v['matchIid']=v['iid'];})
				$.post('/business/product/matchlist', {'relationguid':relationguid,'productInfoItems':JSON.stringify(postData)}, function(res){
					if(res.productlist.code==0){
						if(res.productlist.count==0){
							layer.msg('无匹配项！',{icon:7});
						}else{
							$.each(res.productlist.data,function(j,k){
								$.each(listData,function(i,v){
									if(k.matchIid==v.iid)$.each(res.foldRelation.gridFields,function(k2,v2){if(k[v2])v[k2]=k[v2];});//防止赋空值
								})
							})
							listData = calcDetail(listData);
							layer.msg(res.productlist.msg,{icon:1});
							table.reload('dhtable', {data : listData});
						}
					}else{
						layer.msg(res.productlist.msg,{icon:2});
					}
				});
				break;
			case 'importChange': //修改导入（以型号、行号匹配）
				layer.closeAll();
				var inputObj=document.createElement('input');
				inputObj.setAttribute('type','file');
				inputObj.setAttribute('accept','.xls,.xlsx');
				inputObj.setAttribute("style",'display:none');
				document.body.appendChild(inputObj);
				inputObj.click();
				inputObj.remove();
				$(inputObj).change(function(event) {
					var reader = new FileReader();
					reader.onload = function(e) {
						var xlsFile = XLSX.read(e.target.result, {type: 'binary',cellDates: true,dateNF: 'yyyy-MM-dd'});
						var xlsData = XLSX.utils.sheet_to_json(xlsFile.Sheets[xlsFile.SheetNames[0]]);
						var requiredFlag = true;
						$(xlsData).each(function(ii,vv){
							if(!(vv['*行号'] || vv['行号']))requiredFlag = false;
							if(!(vv['*型号'] || vv['型号']))requiredFlag = false;
						});
						if(requiredFlag){
							$.each(table.cache.dhtable,function(i,v){
								$(xlsData).each(function(ii,vv){
									if(v.gID == (vv['*型号'] || vv['型号']) && v.iid == (vv['*行号'] || vv['行号'])){//表格数据与excel数据以型号为准，改变导入模板对应数据
										$.each(importFields,function(j,k){
											if (vv[j] && !fieldFrontEditList.includes(k)) { //excel数据对应字段存在对应值并且允许修改
												if(decimalObj[k])v[k] = Number(vv[j]).toFixed(decimalObj[k]);//数值类型
												else v[k] = vv[j];
											}
										})
									}
								})
							})
							calcDetail(table.cache.dhtable);
							table.reload('dhtable');
						}else $.modal.msgError('请提供行号、型号进行匹配！');
					};
					reader.readAsBinaryString(inputObj.files[0]);
				});
				break;
			case 'importTable'://导入表格
				layer.closeAll();
				var inputObj=document.createElement('input');
				inputObj.setAttribute('type','file');
				inputObj.setAttribute('accept','.xls,.xlsx');
				inputObj.setAttribute("style",'display:none');
				document.body.appendChild(inputObj);
				inputObj.click();
				inputObj.remove();
				$(inputObj).change(function(event) {
					var reader = new FileReader();
					reader.onload = function(e) {
						var xlsFile = XLSX.read(e.target.result, {type: 'binary',cellDates: true,dateNF: 'yyyy-MM-dd'});
						var xlsData = XLSX.utils.sheet_to_json(xlsFile.Sheets[xlsFile.SheetNames[0]]);
						$(xlsData).each(function(i,v){
							var newData = {};
							$.each(gridColumns.fieldNameRequiredList, function(ii, vv){//循环必填字段
								if(v[vv] || v['*'+vv])newData[gridColumns.fieldRequiredList[ii]] = v[vv] || v['*'+vv];
					    	});
							$.each(importFields,function(ii,vv){
								if (v[ii] && !fieldFrontEditList.includes(vv)) { //excel数据对应字段存在对应值并且允许修改
									if(decimalObj[vv])newData[vv] = Number(v[ii]).toFixed(decimalObj[vv]);//数值类型
									else newData[vv] = v[ii];
								}
							})
							table.cache.dhtable.push(newData);
						})
						listData = calcDetail(table.cache.dhtable);
						table.reload('dhtable',{data: listData});
					};
					reader.readAsBinaryString(inputObj.files[0]);
				});
				break;
			case 'change'://修改
				layer.open({
					type: 1,
					area: [($(window).width() - 400)+'px', ($(window).height() - 200)+'px'],
					fix: false,//不固定
					offset: '10%',//距离顶部
					maxmin: true,//最大最小化
					shade: 0.3,//遮罩
					title: $(this).text(),//按钮名称
					content: $('#btnChange').html(),
					btn: ['保存', '取消'],
					shadeClose: true,// 弹层外区域关闭
					success: function(layero, index){
						var layCols=[{type: "numbers",fixed: "left",width: 40}];
						$.each(gridColumns.dictionaryForPageFieldList,function(i,v){
							if(v.fieldExceptEdit){
								$.each(gridColumns.gridBody,function(ii,vv){
									if(v.fields == vv.field){
										layCols.push(vv);
										if($.inArray(v.fieldFrontType,['t_text','t_decimal']) == -1)layCols[layCols.length-1]['templet'] = '#'+v.fieldFrontType.split('_')[1] + '_' + v.fields;
										else layCols[layCols.length-1]['edit'] = 'text';//默认除特殊模板都可编辑
									}
								})
							}
						})
						$.each(k_fields,function(i,v){
							if(v.fieldExceptEdit){
								if(v.fieldFrontType=='t_date')laydate.render({elem:'.layui-layer #'+v.fields,type:'date',trigger:'click'});
								if(v.fieldFrontType=='t_datetime')laydate.render({elem:'.layui-layer #'+v.fields,type:'datetime',trigger:'click'});
							}
						})
						form.render();
						function tableDate(res, listData){
							$(".layui-table-date").each(function (i) {
								laydate.render({
									elem: this,
									type: 'date',
									trigger: 'click',
									done: function (value, date) {
										var elemtr = $(this.elem).parents('tr').index();
										var elem = $(this.elem).parents('td');
										var datafield = elem.attr("data-field");
										if (res && listData[elemtr]) {
											listData[elemtr][datafield] = value;
										}
									}
								});
							});
						}
						$.tablelist.init({
							elem: '#dhtable_c'
							,data: table.cache.dhtable
							,page: false
							,even: true
							,limit: 1000
							,totalRow: true
							,cols: [layCols
							]
							,height:'full-'+(300 + layero.find('.layui-form').outerHeight(true))
							,done:function(res, curr, count){
								tableDate(res, listData);//日期控件
								$.each(layCols,function(i,v){
									if(!v.edit && v.templet && v.templet.indexOf("templet")>0)$("[lay-id='dhtable_c'] .layui-table-main [data-field='"+v.field+"']").css('background-color','#F2F2F2');
								});
							}
						});
					},
					yes: function(index, layero){
						$.each(listData,function(i,v){
							$.each(all_fields,function(ii,vv){
								if(vv.fieldExceptEdit)v[vv.fields]=layero.find('#'+vv.fields).val();
							})
						})
						$.operate.post(moduleUrl+'/xgxxpost', {'infoItems':JSON.stringify(listData)}, function(res){
							if(res.code == 0){
								goUrl(moduleUrl+'/edit?nid='+nid);
							}
						});
					}
				});
				break;
		};
	});
}
function kdniao(){//轨迹查询——快递鸟——即时查询(增值版)
	var params='';
	$.each(all_fields,function(i,v){
		switch(v.fieldStandard.toLowerCase()){
			case 'vshrdh'://手机号
				params += '&client=' + v.fieldContent;
				break;
			case 'vfhwlname'://快递公司
				params += '&expCode=' + encodeURIComponent(v.fieldContent);
				break;
			case 'vhydh'://快递单号
				params += '&expNo=' + v.fieldContent;
				break;
		}
	})
	$.modal.openSimple('物流轨迹','/common/kdniao?' + params,($(window).width() - 400),($(window).height() - 200));
}
//表格编辑——资金计算
function moneyCalculation(){
	var totalList={};
	$.each(gridColumns.gridBody,function(i,v){
		if(v.totalRow && !v.hide)totalList[v.field]=i;//统计合计列数组
	})
	table.on('edit(ftable)', function(obj){
		if(obj.field in decimalObj){//判断编辑单元格是否数值字段
			var selector = obj.tr.selector+' td[data-field="'+obj.field+'"] div',//获取当前单元格对象
				dataindex = obj.tr[0].rowIndex,//编辑单元格下标
				editField = obj.field,//编辑单元格fieId
				editRow = obj.data,//编辑单元格行数据
				oldtext = $(selector).text(),// 单元格编辑之前的值
				editValue = checkEdit(obj, decimalObj),//判断输入的值是否是数值，是则返回对应字符串，否则返回false
				dj=useHs?'bPrice':'fWsDj',
				mj=useHs?'fHsMj':'fWsMj';//根据全局系统设置，以含税、未税面价进行单价与折扣互算
			if(editValue){//输入的是数值
				for(var v of ['bNumb','bPrice','fWsDj','fHsMj','fWsMj','fBjzk','fHtzk','fCgZk']){
					editRow[v] = Number(editRow[v]?editRow[v]:0).toFixed(decimalObj[v]);//为空时赋值0
				}
				var SL = $("#fCgFpSl").val()?$("#fCgFpSl").val():listData[dataindex]['fCgFpSl'];//采购税率——优先选取表头，后明细
				if(!SL)SL = $("#fXsFpsl").val()?$("#fXsFpsl").val():listData[dataindex]['fXsFpsl'];//没有采购税率则取销售税率
				SL = SL || 0;//不存在税率时则赋0
				switch(editField){
					case 'fBjzk'://计算含税单价、未税单价
					case 'fHtzk':
					case 'fCgZk':
						editRow[dj] = Number(editValue * editRow[mj]).toFixed(decimalObj[dj]);//单价=折扣*面价
						if(useHs)editRow.fWsDj = Number(editRow.bPrice / (1 + SL/100)).toFixed(decimalObj.fWsDj);//未税单价=含税单价/(1+税率/100)
						else editRow.bPrice = Number(editRow.fWsDj * (1 + SL/100)).toFixed(decimalObj.bPrice);//含税单价=未税单价*(1+税率/100)
						break;
					case 'bPrice'://计算折扣、未税单价
						editRow.fWsDj = Number(editValue / (1 + SL/100)).toFixed(decimalObj.fWsDj);//未税单价=含税单价/(1+税率/100)
						editRow.fBjzk = Number(editRow[mj])?Number(editRow[dj] / editRow[mj]).toFixed(decimalObj.fBjzk || decimalObj.fHtzk || decimalObj.fCgZk):0;
						break;
					case 'fWsDj'://计算折扣、含税单价
						editRow.bPrice = Number(editValue * (1 + SL/100)).toFixed(decimalObj.bPrice);//含税单价=含税面价*(1+税率/100)
						editRow.fBjzk = Number(editRow[mj])?Number(editRow[dj] / editRow[mj]).toFixed(decimalObj.fBjzk || decimalObj.fHtzk || decimalObj.fCgZk):0;
						break;
					case 'fSumje'://金额==>单价or数量==》计算折扣、未税单价
						if(Number(editRow.bNumb))editRow.bPrice = Number(editValue / editRow.bNumb).toFixed(decimalObj.bPrice);//单价=金额/数量
						else if(Number(editRow.bPrice)){
							editRow.bNumb = Number(editValue / editRow.bPrice).toFixed(decimalObj.bNumb);//单价=金额/单价
							editRow.bPrice = Number(editValue / editRow.bNumb).toFixed(decimalObj.bPrice);//单价=金额/数量==>防止金额不匹配
						}else{//不存在单价和数量则全部赋值为0
							editRow.bNumb = Number(0).toFixed(decimalObj.bNumb);
							editRow.bPrice = Number(0).toFixed(decimalObj.bPrice);
							editRow.fSumje = Number(0).toFixed(decimalObj.fSumje);
							editValue = Number(0).toFixed(decimalObj.fSumje);
						}
						editRow.fWsDj = Number(editRow.bPrice / (1 + SL/100)).toFixed(decimalObj.fWsDj);//未税单价=含税单价/(1+税率/100)
						editRow.fBjzk = Number(editRow[mj])?Number(editRow[dj] / editRow[mj]).toFixed(decimalObj.fBjzk || decimalObj.fHtzk || decimalObj.fCgZk):0;
						break;
				}
				if(Number(editRow.fPsCb) || Number(editRow.fPsCbHs)){//针对被退回的评审（销售报价、销售合同、销售合同清单），计算相关金额
					if(useHs){//以含税评审成本为主
						editRow.fPsCb = Number(editRow.fPsCbHs / (1 + SL/100)).toFixed(decimalObj.fPsCb);
						editRow.fPsZk = (Number(editRow.fHsMjT)?Number(editRow.fPsCbHs / editRow.fHsMjT):0).toFixed(decimalObj.fPsZk);// 评审折扣
					}else{//以未税评审成本为主
						editRow.fPsCbHs = Number(editRow.fPsCb * (1 + SL/100)).toFixed(decimalObj.fPsCbHs);
						editRow.fPsZk = (Number(editRow.fWsMjT)?Number(editRow.fPsCb / editRow.fWsMjT):0).toFixed(decimalObj.fPsZk);// 评审折扣
					}
					editRow.fXsPsBl = (Number(editRow.fPsCbHs)?Number(editRow.bPrice / Number(editRow.fPsCbHs)):0).toFixed(decimalObj.fXsPsBl);//销售评审比例=单价/评审成本
					editRow.fPsJe = Number(editRow.fPsCb * editRow.bNumb).toFixed(decimalObj.fPsJe);//评审金额
					editRow.fPsJeHs = Number(editRow.fPsCbHs * editRow.bNumb).toFixed(decimalObj.fPsJeHs);//含税评审金额
					editRow.fPsMl = Number(editRow.bNumb * (editRow.bPrice - editRow.fPsCbHs)).toFixed(decimalObj.fPsMl);//单项毛利
					editRow.fPsMll = (Number(editRow.bPrice)?Number((editRow.bPrice - editRow.fPsCbHs)/editRow.bPrice):0).toFixed(decimalObj.fPsMll);//评审毛利率
				}
				if (typeof specialTableCalculation == 'function') editRow = specialTableCalculation(editRow); //表格特殊计算
				editRow.fHtzk = editRow.fCgZk = editRow.fBjzk;
				editRow.fSumje = Number(editRow.bPrice * editRow.bNumb).toFixed(decimalObj.fSumje);//合同金额=含税单价*数量
				editRow.fWsJe = Number(editRow.fWsDj * editRow.bNumb).toFixed(decimalObj.fSumje);//未税金额=未税单价*数量
//				editRow.fWsJe = Number(editRow.fSumje / (1 + SL/100)).toFixed(decimalObj.fWsJe);//未税金额=合同金额/(1+税率/100)
				editRow.fSe = Number(editRow.fSumje - editRow.fWsJe).toFixed(decimalObj.fSe);//税额=合同金额-未税金额

				var updateR={};
				$.each(editRow,function(i,v){
					if(v != listData[dataindex][i]){
						table.cache.dhtable[dataindex][i] = v;
						updateR[i]=editRow[i];//只更新发生变化的数据，防止其他控件需要重新渲染
					}
				})
				obj.update(updateR);

				if(editField == 'bPrice'){//实际进价的计算（隐藏时实时更新，显示时为空赋值）
					$.each(gridColumns.gridBody,function(i,v){
						if(v.field=='fPrice'){
							if(v.hide=="true")listData[dataindex]['fPrice'] = Number(editValue).toFixed(decimalObj.fPrice);
							else if(!editRow.fPrice)listData[dataindex]['fPrice'] = Number(editValue).toFixed(decimalObj.fPrice);
							obj.update({fPrice: listData[dataindex]['fPrice']});
						}
					})
				}
				if(listData[dataindex]['bPrice']!=null && listData[dataindex]['gPrice']!=null && listData[dataindex]['bNumb']!=null){//存在单价、成本价、数量时==>计算单项毛利
					listData[dataindex]['fDxMl']=Number(listData[dataindex]['bNumb'] * (listData[dataindex]['bPrice']-listData[dataindex]['gPrice'])).toFixed(decimalObj.fDxMl);//单项毛利
					obj.update({fDxMl: listData[dataindex]['fDxMl']});
				}
				$.each(totalList,function(i,v){//重新计算统计字段数值
					if(i==editField){//编辑单元格为合计列时更新错误（单元格值的改变在监听后）
						$('.laytable-cell-1-0-'+v).last().text(Number(Number($('.laytable-cell-1-0-'+v).last().text())-Number(oldtext)+Number(editValue)).toFixed(decimalObj[i]));
					}else{
						var totalSum=0;
						$.each($('.laytable-cell-1-0-'+v),function(j,k){
							if(j>0 && j<$('.laytable-cell-1-0-'+v).length-1)totalSum+=Number($(k).text());//第一个是标题，最后一个是统计行
							if(j==$('.laytable-cell-1-0-'+v).length-1)$(k).text(totalSum.toFixed(decimalObj[i]));
						})
					}
				})
			}else editValue = oldtext;//返回false，即输入不是数值，还原数值
			setTableValue('dhtable', dataindex, editField, editValue);//通过dom给表格内控件渲染值
			listData[dataindex][editField] = editValue;
			if(editRow.fPsCbHs){//重新计算整单毛利率
				var sumBPrice=0,sumFPsCb=0;
				$.each(listData,function(k,v){
					sumBPrice+=(v.bPrice*(v.bNumb-(v.fThSl?v.fThSl:0)));
					sumFPsCb+=(v.fPsCbHs*(v.bNumb-(v.fThSl?v.fThSl:0)));
				});
				$('#fZdPsMll').val((sumBPrice?((sumBPrice-sumFPsCb)/sumBPrice * 100):0).toFixed(decimalObj.fPsMll)+ "%");//整单评审毛利率计算赋值
			}
		}
	});
}
//监听排序事件——非url加载只能对数据重新排序——重载赋值渲染
function monitorSort(){
	table.on('sort(ftable)', function(obj){
		for(var i=0; i<listData.length-1; i++){//冒泡排序
			for(var j=0; j<listData.length-i-1; j++){
				switch(obj.type){
					case 'asc'://根据当前字段升序排序
						if(listData[j][obj.field]>listData[j+1][obj.field])listData[j]=[listData[j+1],listData[j+1]=listData[j]][0];
						break;
					case 'desc'://根据当前字段降序排序
						if(listData[j][obj.field]<listData[j+1][obj.field])listData[j]=[listData[j+1],listData[j+1]=listData[j]][0];
						break;
					default://默认根据iid升序排序
						if(listData[j]['iid']>listData[j+1]['iid'])listData[j]=[listData[j+1],listData[j+1]=listData[j]][0];
						break;
				}
			}
		}
		table.reload('dhtable', {data:listData,initSort: obj});
		if(!gridColumns.readOnly)tableDone(listData,fieldFrontEditList);//非只读情况下的动作集
		showloadings(false);
		detailUpload();
	});
}
//下拉可编辑——表头(field)
function changeDropdown(lx){
	form.on('select('+lx+'_select)', function (data) {//监听下拉框，动态赋值
		$("#"+lx).val(data.value);
		form.render();////修复下拉框选中后无法消失的问题
	});
	//下拉可编辑，编辑时过滤选项
	window.inputSearch=function() {
		console.log('表头');
		$("#"+lx).val($("#"+lx).val());
		var value = $("#"+lx).val();
		$("#"+lx+"_select").val(value);
		form.render();
		$("#"+lx+"_select").next().find("dl").css({ "display": "block" });
		var dl = $("#"+lx+"_select").next().find("dl").children();
		var j = -1;
		for (var i = 0; i < dl.length; i++) {
			if (dl[i].innerHTML.indexOf(value) <= -1) {
				dl[i].style.display = "none";
				j++;
			}
			if (j == dl.length-1) {
				$("#"+lx+"_select").next().find("dl").css({ "display": "none" });
			}
		}
	}
}
//下拉可编辑——表头(field)——报价税率
function changeFpsl(lx){
	form.on('select('+lx+'_select)', function (data) {//监听下拉框，动态赋值
		$("#"+lx).val(Math.round(data.value));
		form.render();//修复下拉框选中后无法消失的问题
		updatefWsDj(Math.round(data.value));//更新未税单价
	});
	//下拉可编辑，编辑时过滤选项
	window.inputTopFpsl=function(obj,lx) {
		console.log('报价');
		$("#"+lx).val(Math.round($("#"+lx).val()));
		var value = $("#"+lx).val();
		$("#"+lx+"_select").val(value);
		form.render();
		$("#"+lx+"_select").next().find("dl").css({ "display": "block" });
		var dl = $("#"+lx+"_select").next().find("dl").children();
		var j = -1;
		for (var i = 0; i < dl.length; i++) {
			if (dl[i].innerHTML.indexOf(value) <= -1) {
				dl[i].style.display = "none";
				j++;
			}
			if (j == dl.length-1) {
				$("#"+lx+"_select").next().find("dl").css({ "display": "none" });
			}
		}
	}
	$("#"+lx).change(function(){
		updatefWsDj( $("#"+lx).val());				//更新未税单价
	})
}
//下拉可编辑——明细(field,listData)
function changeDropdownInTable(lx,ld){
	form.on('select('+lx+'_select)', function (data) {//监听下拉框，动态赋值
		console.log(data);
		$(data.elem.parentElement).find('input').val(data.value);
		ld[$(data.elem.parentElement).parents('tr').index()][lx]=data.value;
		form.render();////修复下拉框选中后无法消失的问题
	});
}
//下拉可编辑——明细(field,listData)——报价税率
function changeFpslInTable(lx,ld){
	form.on('select('+lx+'_select)', function (data) {//监听下拉框，动态赋值
		$(data.elem.parentElement).find('input').val(data.value);
		ld[$(data.elem.parentElement).parents('tr').index()][lx]=data.value;
		form.render();//修复下拉框选中后无法消失的问题
		updateSlInTable($(data.elem.parentElement).parents('tr').index(),data.value);//更新未税单价
	});
}
//编辑时同时赋值到明细表数据listdata中
window.inputSearchTable=function (obj,field){
	console.log('明细');
	listData[$(obj).parents('tr').index()][field]=obj.value;
	if(field == 'fXsFpsl' || field =='fCgFpSl')updateSlInTable($(obj).parents('tr').index(),obj.value);//更新未税单价
}
//更新税率——资金计算
function updatefWsDj(fXsFpsl){
	showloadings(true);
	for(var i = 0; i < listData.length; i++){
		updateSlInTable(i,fXsFpsl);
	}
	showloadings(false);
}
//更新税率——单条明细
function updateSlInTable(i,fXsFpsl){
	listData[i]['bPrice'] = Number((listData[i]['bPrice']?listData[i]['bPrice']:0));//以含税单价为主
	listData[i]['fWsDj'] = Number((listData[i]['bPrice']?listData[i]['bPrice']:0) / (1 + fXsFpsl/100)).toFixed(decimalObj.fWsDj);//未税单价
	if(useHs)listData[i]['fBjzk'] = Number(Number(listData[i]['fHsMj'])?(listData[i]['bPrice']/listData[i]['fHsMj']):0).toFixed(decimalObj.fBjzk || decimalObj.fHtzk || decimalObj.fCgZk);
	else listData[i]['fBjzk'] = Number(Number(listData[i]['fWsMj'])?(listData[i]['fWsDj']/listData[i]['fWsMj']):0).toFixed(decimalObj.fBjzk || decimalObj.fHtzk || decimalObj.fCgZk);
	listData[i]['fCgZk'] = listData[i]['fHtzk'] = listData[i]['fBjzk'];//采购折扣、合同折扣、报价折扣
	listData[i]['fSumje'] = Number(listData[i]['bPrice'] * listData[i]['bNumb']).toFixed(decimalObj.fSumje);//合同金额=含税单价*数量
	listData[i]['fWsJe'] = Number(listData[i]['fWsDj'] * listData[i]['bNumb']).toFixed(decimalObj.fSumje);//未税金额=未税单价*数量
	listData[i]['fSe'] = Number(listData[i]['fSumje']-listData[i]['fWsJe']).toFixed(decimalObj.fSe);
	setTableValue('dhtable', i, 'fBjzk', listData[i]['fBjzk']);
	setTableValue('dhtable', i, 'fHtzk', listData[i]['fHtzk']);
	setTableValue('dhtable', i, 'fCgZk', listData[i]['fCgZk']);
	setTableValue('dhtable', i, 'fWsDj', listData[i]['fWsDj']);
	setTableValue('dhtable', i, 'fSumje', listData[i]['fSumje']);
	setTableValue('dhtable', i, 'fWsJe', listData[i]['fWsJe']);
	setTableValue('dhtable', i, 'fSe', listData[i]['fSe']);
	if(Number(listData[i]['fPsCb']) || Number(listData[i]['fPsCbHs'])){//针对被退回的评审（销售报价、销售合同、销售合同清单），计算相关金额
		if(useHs){//以含税评审成本为主
			listData[i]['fPsCb'] = Number(listData[i]['fPsCbHs'] / (1+ fXsFpsl/100)).toFixed(decimalObj.fPsCb);
			listData[i]['fPsZk'] = (Number(listData[i]['fHsMjT'])?Number(listData[i]['fPsCbHs'] / listData[i]['fHsMjT']):0).toFixed(decimalObj.fPsZk);// 评审折扣
		}else{//以未税评审成本为主
			listData[i]['fPsCbHs'] = Number(listData[i]['fPsCb'] * (1+ fXsFpsl/100)).toFixed(decimalObj.fPsCbHs);
			listData[i]['fPsZk'] = (Number(listData[i]['fWsMjT'])?Number(listData[i]['fPsCb'] / listData[i]['fWsMjT']):0).toFixed(decimalObj.fPsZk);// 评审折扣
		}
		listData[i]['fXsPsBl'] = (Number(listData[i]['fPsCbHs'])?Number(listData[i]['bPrice'] / Number(listData[i]['fPsCbHs'])):0).toFixed(decimalObj.fXsPsBl);//销售评审比例=单价/评审成本
		listData[i]['fPsJe'] = Number(listData[i]['fPsCb'] * listData[i]['bNumb']).toFixed(decimalObj.fPsJe);//评审金额
		listData[i]['fPsJeHs'] = Number(listData[i]['fPsCbHs'] * listData[i]['bNumb']).toFixed(decimalObj.fPsJeHs);//含税评审金额
		listData[i]['fPsMl'] = Number(listData[i]['bNumb'] * (listData[i]['bPrice'] - listData[i]['fPsCbHs'])).toFixed(decimalObj.fPsMl);//单项毛利
		listData[i]['fPsMll'] = (Number(listData[i]['bPrice'])?Number((listData[i]['bPrice'] - listData[i]['fPsCbHs'])/listData[i]['bPrice']):0).toFixed(decimalObj.fPsMll);//评审毛利率
		setTableValue('dhtable', i, 'fPsCb', listData[i]['fPsCb']);
		setTableValue('dhtable', i, 'fPsCbHs', listData[i]['fPsCbHs']);
		setTableValue('dhtable', i, 'fPsZk', listData[i]['fPsZk']);
		setTableValue('dhtable', i, 'fXsPsBl', listData[i]['fXsPsBl']);
		setTableValue('dhtable', i, 'fPsJe', listData[i]['fPsJe']);
		setTableValue('dhtable', i, 'fPsJeHs', listData[i]['fPsJeHs']);
		setTableValue('dhtable', i, 'fPsMl', listData[i]['fPsMl']);
		setTableValue('dhtable', i, 'fPsMll', listData[i]['fPsMll']);
	}
}
//表格初始化之前的动作集合
function beforeInit(){
	if(nid==0){//制单时字段默认值初始赋值
		$.each(all_fields,function(i,k){
			if(k.fieldFrontValue){
				if(k.fieldFrontValue.substring(0,1)=='#')$('#'+k.fields).val($(k.fieldFrontValue).val());//获取当前dom的节点数据
				else if(k.fieldFrontValue=='getdate()')k.fieldFrontType=='t_date'?$('#'+k.fields).val(getDate()):$('#'+k.fields).val(getTime());
				else{
					if(k.fieldFrontType=="t_file") $('#'+k.fields).val();
					else $('#'+k.fields).val(k.fieldFrontValue);
				} 
			}
		})
	}else{//非制单时开启指定字段可编辑
		if(gridColumns.readOnly)$.each(k_fields,function(i,k){
			if(k.fieldExceptEdit && buttonState['tp-save']=='enable'){
				$('#'+k.fields).removeClass('canntEdit');
				$('#'+k.fields)[0].readOnly=false;
			}
		})
	}
	//遍历表头字段——下拉框赋值、时间控件渲染、下拉可编辑添加动作集
	$.each(k_fields,function(k,v){
		if(v.fieldFrontValue){
			var fieldFrontArr=v.fieldFrontValue.split(",");
			if(fieldFrontArr.length==2){
				var isval= $("#"+fieldFrontArr[0]).val()
				if(!isval){
					$("#"+v.fields).addClass('canntEdit')
					$("#"+v.fields).siblings('i').hide()
				} 
			} 
		}

		if(v.fieldFrontType=="t_dropdown" && !gridColumns.readOnly && v.fieldFrontSave!=v.fieldFrontShow && !!v.fieldMatched && v.fieldFrontEdit)$('#'+v.fieldMatched.split(',')[0]).val($('#'+v.fields).val());//表头下拉框的隐藏框赋值（非只读）
		if((v.fieldFrontType=="t_date" || v.fieldFrontType=="t_datetime" || v.fieldFrontType=="t_year" || v.fieldFrontType=="t_monthly") && v.fieldFrontEdit && !gridColumns.readOnly){//表头时间控件渲染（非只读）
			$('#'+v.fields).unbind();//清除事件，防止重复监听
			$('#'+v.fields).on('change',function(){//手动修改日期
				var errorMsg = '';//错误提示
				switch(v.fieldFrontType){
					case 't_date':
						if(judgeStrDate($('#'+v.fields).val())){//验证日期格式
							var r = $('#'+v.fields).val().match(/^(\d{1,4})(-|\/|.)(\d{1,2})\2(\d{1,2})$/);
							if(typeof judgeTopDate == 'function'){
								judgeTopDate('#'+v.fields,formatDate(new Date(r[1], r[3]-1, r[4]),'date'));
							}else $('#'+v.fields).val(formatDate(new Date(r[1], r[3]-1, r[4]),'date'));
						}else errorMsg = '请输入正确时间格式，形如2020-01-01';
						break;
					case't_datetime':
						if(judgeStrDateTime($('#'+v.fields).val())){//验证日期时间格式
							var r = $('#'+v.fields).val().match(/^(\d{1,4})(-|\/|.)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
							if(typeof judgeTopDate == 'function'){
								judgeTopDate('#'+v.fields,formatDate(new Date(r[1], r[3]-1, r[4], r[5], r[6], r[7])));
							}else $('#'+v.fields).val(formatDate(new Date(r[1], r[3]-1, r[4], r[5], r[6], r[7])));
						}else errorMsg = '请输入正确时间格式，形如2020-01-01 00:00:00'; 
						break;
					case 't_year':
						if(judgeStrYear($('#'+v.fields).val())){//验证年份格式
							var r = $('#'+v.fields).val().match(/^(\d{1,4})$/);
							if(typeof judgeTopDate == 'function'){
								judgeTopDate('#'+v.fields,formatDate(new Date(r[1]),'year'));
							}else $('#'+v.fields).val(formatDate(new Date(r[1]),'year'));
						}else errorMsg = '请输入正确时间格式，形如2020';
						break;
					case 't_monthly':
						if(judgeStrYear($('#'+v.fields).val())){//验证年份格式
							// var r = $('#'+v.fields).val().match(/^(\d{1,4})(-|\/|.)(\d{1,2})$/);
							if(typeof judgeTopDate == 'function'){
								judgeTopDate('#'+v.fields,formatDate(new Date(r[1]),'month'));
							}else $('#'+v.fields).val(formatDate(new Date(r[1]),'month'));
						}else errorMsg = '请输入正确时间格式，形如2022-01';
						break;
				}
				if(errorMsg){//如果存在错误提示，则清空控件内容并提示错误
					$('#'+v.fields).val('');
					layer.msg(errorMsg);
				}
			})
			console.log("1",v.fields+'_date',v.fieldFrontType.substring(2,v.fieldFrontType.length),v.fieldFrontType)
			laydate.render({
				elem:'#'+v.fields+'_date',
				type:v.fieldFrontType === 't_monthly' ? 'month': v.fieldFrontType.substring(2,v.fieldFrontType.length),
				trigger:'click',
				done:function(value, date){
					if(typeof judgeTopDate == 'function')judgeTopDate('#'+v.fields,value);//存在日期判断则执行
					else $('#'+v.fields).val(value);//原输入控件赋值
					if (v.fields == 'hwMonth'){
						table.reload('dhtable', {data:[]});
						table.reload('cktable', {data:[]});
						table.reload('kctable', {data:[]});
						$('#warehouseAddress').val(null)
					}
				}
			});
		}
		if(v.fieldFrontType=="t_dropdownedit" && v.fieldFrontEdit && !gridColumns.readOnly){//下拉可编辑
			if(v.fields == 'fXsFpsl' || v.fields =='fCgFpSl')changeFpsl(v.fields);
			else changeDropdown(v.fields);
		}
		if(v.fieldFrontEdit == true && v.fieldFrontType=='t_buttontextedit'){//可编辑弹出框
			var fd=v.fields;
			window.inputOnTop=function (obj,fd){//手动输入时，赋空隐藏或不可编辑的被联动字段（年度培训计划：培训讲师pUser、出差申请：客户编号gClient等）
				$.each(all_fields,function(j,k){//循环所有非数据表格字段，联动一次
					if(k.fieldMatched == fd && (!k.fieldFrontEdit || [2,6,8].includes(k.fieldFrontTop)))$('#'+k.fields).val('');
				})
			}
		}
	});
	//监听表头下拉框事件——下拉框联动
	form.on('select(select_top)',function(e){
		if(e.elem.dataset['fieldfrontsave']!=e.elem.dataset['fieldfrontshow']){
			if(!!e.elem.dataset['fieldmatched']){
				$.each(e.elem.dataset['fieldmatched'].split(','), function (i, v) {
					switch (e.elem.dataset['fieldfrontsave'].split(',')[i].toLowerCase()) {
						case 'vid':
							$('#' + v).val(e.value);
							break;
						case 'vname':
							$('#' + v).val(e.elem.selectedOptions[0].text);
							break;
						case 'fvalue':
							$('#' + v).val(e.elem.selectedOptions[0].dataset.fvalue);
							break;
						case 'vremark':
							$('#' + v).val(e.elem.selectedOptions[0].dataset.vremark);
							break;
					}
				})
			}
		}
	});
	//监听弹出层下拉框事件——下拉框联动
	form.on('select(select_layer)',function(e){
		if(e.elem.dataset['fieldfrontsave']!=e.elem.dataset['fieldfrontshow']){
			if(!!e.elem.dataset['fieldmatched']){
				$.each(e.elem.dataset['fieldmatched'].split(','), function (i, v) {
					switch (e.elem.dataset['fieldfrontsave'].split(',')[i].toLowerCase()) {
						case 'vid':
							$('#' + v).val(e.value);
							break;
						case 'vname':
							$('#' + v).val(e.elem.selectedOptions[0].text);
							break;
						case 'fvalue':
							$('#' + v).val(e.elem.selectedOptions[0].dataset.fvalue);
							break;
						case 'vremark':
							$('#' + v).val(e.elem.selectedOptions[0].dataset.vremark);
							break;
					}
				})
			}
		}
	});
	//查询流程
	$('.layui-icon-search').click(function(){
		if(!!$('#procInstId').val()){
			var width = $(window).width()<800?($(window).width()-100):800;
			var height = ($(window).height() - 150);
			var url = "/flowable/process/processSpeed/"+ $('#procInstId').val();
			layer.open({
				type: 2,
				area: [width + 'px', height + 'px'],
				offset: '10%',//距离顶部10%
				fix: false,
				//不固定
				maxmin: true,
				shade: 0.6,
				title: "流程跟踪",
				content:  url,
				btn: ['关闭'],
				//点击弹层外区域关闭
				shadeClose: true,
				cancel: function(index) {
					return true;
				}
			});
		}else{
			var url = "/flowable/definition/flowsheetbykey?procDefKey="+moduleTable;
			var width = $(window).width()<800?($(window).width()-100):800;
			var height = ($(window).height() - 150);
			layer.open({
				type: 2,
				area: [width + 'px', height + 'px'],
				offset: '10%',//距离顶部10%
				fix: false,
				//不固定
				maxmin: true,
				shade: 0.6,
				title: "流程图",
				content:  url,
				btn: ['关闭'],
				//点击弹层外区域关闭
				shadeClose: true,
				cancel: function(index) {
					return true;
				}
			});
		}
	})
	form.render();//结束前渲染，防止控件设置默认值不生效(下拉控件等)
}
//只读情况下可编辑(暂未使用)
function readonlyEdit(){
	if(gridColumns.readOnly){
		$.each(gridColumns.dictionaryForPageFieldList,function(i,v){
			if(v.fieldExceptEdit && buttonState['tp-save']=='enable')$('thead').find('th[data-field='+v.fields+']').attr('style','background:#5FB878;color:#fff;');
		})
	}
}
//导入数据
function importListExcel(obj, importFields, mName) {
	var wb;//读取完成的数据
	var rABS = false; //是否将文件读取为二进制字符串
	var iid;
	if(!obj.files) {
		return;
	}
	const IMPORTFILE_MAXSIZE = 1*2048;       //这里可以自定义控制导入文件大小
	var suffix = obj.files[0].name.split(".").slice(-1);
	if(suffix != 'xls' && suffix !='xlsx'){
		layer.msg('导入的文件格式不正确!')
		return
	}
	if(obj.files[0].size/1024 > IMPORTFILE_MAXSIZE){
		layer.msg('导入的表格文件不能大于2M')
		return
	}
	showloadings(true);
	var f = obj.files[0];
	var reader = new FileReader();
	var reStr='';
	reader.onload = function(e) {
		var data = e.target.result;
		if(rABS) {
			wb = XLSX.read(btoa(fixdata(data)), {     //手动转化
				type: 'base64'
			});
		} else {
			wb = XLSX.read(data, {
				type: 'binary'
			});
		}
		var strForm=XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
		var excelData = [], tStr = trStr='';
		hasNull = false;
		for(var i=0; i<strForm.length; i++){
			var trData = {},strFormTr = {};
			$.each(strForm[i], function(si, sv){
				strFormTr[si.replace("*", "")] = sv;
			})
			trStr += '<tr><td style="text-align: center;">' + Number(i+1) + '</td>';
			$.each(importFields,function(j,v){
				tStr = strFormTr[j.replace("*", "")] ? strFormTr[j.replace("*", "")] : '';
				if(mName != "product" && $.inArray(v,dateFiled) > -1)tStr = tStr ? forDate(tStr) : '';
				if(!hasNull &&  j.includes('*') && tStr == ''){
					hasNull = "<p>第<span style='color:red'>"+Number(i+1)+"</span>行必填字段【<span style='color:red'>"+j.replace("*", "")+"</span>】不允许为空！</p>请核对数据，重新导入。";//导入数据必填字段有空值
				}
				trStr += '<td tindex="' + i + '" tfield="' + v + '">' + tStr + '</td>';
				trData[v] = tStr;
			})
			trStr += '</tr>';
			trData['iid'] = Number(i+1);
			excelData.push(trData);
		}
		if(hasNull)layer.alert(hasNull, {icon:7});
		$("#itbody").html(thStr + trStr);
		intable(excelData, mName);
	};
	if(rABS) {
		reader.readAsArrayBuffer(f);
	} else {
		reader.readAsBinaryString(f);
	}
	return true;
}
/*弹出层（导入列表内容）
 * mName：product产品;customer客户;provider供应商;
 */
function intable(listDataObj, mName){
	var dTitle,stepNameMsg;
	switch(mName){
		case 'product':
			dTitle ='导入产品列表';
			break;
		case 'producthistory':
			dTitle = '导入产品历史面价表';
			break;
		case 'customer':
			dTitle = '导入客户列表';
			stepNameMsg = '请选择客户属性！';
			break;
		case 'provider':
			dTitle = '导入供应商列表';
			stepNameMsg = '请选择供应商属性！';
			break;
		case 'user':
			dTitle = '导入用户列表';
			break;
		default:
			dTitle='导入列表';
			break;
	}
	layer.open({
		type: 1,
		area: ['800px', '500px'],
		fix: false,
		offset: '10%',
		maxmin: true,
		shade: 0.3,
		title: dTitle,
		content: $('#iForm').html()?($('#iForm').html()+$('#iTable').html()):$('#iTable').html(),//产品信息扩展iForm
		btn: ['<i class="dhicon dh-check"></i> 确定', '<i class="dhicon dh-remove"></i> 取消'],
		shadeClose: true,
		zIndex: 1001,
		success: function(layero, index){
			showloadings(false);
			form.render();
		},
		btn1: function(index, layero){
			switch(mName){//点击确定导入时的判断
				case 'product':
					var errorRow = [];
					var filterBlankArr = ['gBrand','gID','gModel','gName','gSerial','gUnit'];
					$.each(listDataObj,function(i,v){
						if(v.gBrand == 'AB' && v.gID.indexOf('-') != -1)errorRow.push(i+1);
						$.each(filterBlankArr,function(ii,vv){//【品牌、型号、规格、品名、系列、单位】去除前后空格回车
							if(v[vv])v[vv] = v[vv].replace(/(^\s*)|(\s*$)/g, "").replace(/[\r\n]/g, "");
						})
					})
					if(errorRow.length){
						$.modal.msgError("【AB】品牌下的型号不能带“-”！<br>错误行：第"+errorRow.join(',')+"行！", modal_status.FAIL);
						return false;
					}
				case 'producthistory':
					var iFormData=layero.find('form').serializeFormToJson();
					if(!iFormData.fSl){layer.msg("请选择税率！", {icon:7});return false;}
					if(!iFormData.fType){layer.msg("请选择税额计算相关！", {icon:7});return false;}
					break;
				case 'customer':
				case 'provider':
					cID = $(".layui-layer-page .cid").val();
					if(!cID){layer.msg("请选择所属公司！", {icon:7});return false;}

					bUser = $(".layui-layer-page .bUser").val();
					bDept = $(".layui-layer-page .bDept").val();
					if(!bUser){layer.msg("请选择所属员工！", {icon:7});return false;}

					stepName = $(".layui-layer-page [name='stepName']").val();
					if(!stepName){layer.msg(stepNameMsg, {icon:7});return false;}
					break;
			}
			if(hasNull){
				layer.alert(hasNull, {icon:7});
				return false;
			}
			showloadings(true);
			$("#importProgress").css('display','table-column');
			$(".importProgress").css('display','table-column');
			var importObj = [],
				inum = 0,
				onetime = 1,
				flag = 1,
				oneImportNum = 2, 						//默认一次导入条数
				allImportNum = listDataObj.length, 		//数据总量
				importBl = 0,	//导入进度
				times = 0;		//请求次数
			if(mName == 'product')$.operate.post("/business/product/cleanproductimportpost"); 		//清除导入旧数据
			if(mName == 'producthistory')$.operate.post("/business/producthistory/cleanproductimportpost"); 		//清除导入旧数据
			if(mName == 'productbasis')$.operate.post("/business/productbasis/cleanproductimportpost"); 		//清除导入旧数据
			element.progress('dhprogress', '0%');
			setTimeout(function(){
				if(allImportNum > 9 && allImportNum <= 100){
					oneImportNum = 5;
				}else if(allImportNum > 100 && allImportNum <= 500){
					oneImportNum = 30;
				}else if(allImportNum > 500 && allImportNum <= 1000){
					oneImportNum = 50;
				}else if(allImportNum > 1000){
					oneImportNum = 100;
				}
				times = Math.ceil(allImportNum/oneImportNum);
				eachImport(listDataObj, 0, oneImportNum, allImportNum, times, 1);return false;
			}, 1000);
		}
	});
}
//结束导入，关闭弹出层
function closeProcess(res, mName){
	setTimeout(function(){
		$("#importProgress").css('display','none');
		$(".importProgress").css('display','none');
		layer.closeAll();
		$.operate.ajaxSuccess(res);

		$(".search-field").each(function(i,v){				//当前显示的查询字段(包含.search-field)
			wherestr[v.name]=''
		});
		//动态获取条件的值
		$.each(wherestr,function(i,v){
			if((i.substring(i.length-2,i.length)=='_s' || i.substring(i.length-2,i.length)=='_e') && $("#"+i).attr('fft') != 't_text'){
				if(!$("#"+i.substring(0,i.length-2)).val())wherestr[i]="";
				return;//时间控件的衍生字段需跳出循环
			}
			var vs=$("[name="+i+"]").val();
			switch($("#"+i).attr('fft')){
				case 't_checkcondition':
					if($("#"+i).prop("checked")){
						wherestr[i] = 1;
					}else{
						wherestr[i]='';
					}
					break;
				case 't_radio':
					if($("[name='"+i+"']:checked").val()){
						wherestr[i] = $("[name='"+i+"']:checked").val()
					}else{
						wherestr[i]='';
					}
					break;
				case 't_date':
					wherestr[i+'_s']="";
					wherestr[i+'_e']="";
					if($("#"+i).attr('ffct')=='t_between' && !!$("#"+i).val()){//区间范围的需要切割，而且尾头多出了空格
						var st=vs.split('~');
						wherestr[i+'_s']=st[0].substring(0,st[0].length-1);
						wherestr[i+'_e']=st[1].substring(1,st[1].length);
					}else{
						vs?wherestr[i]=vs:wherestr[i]='';
					}
					break;
				case 't_datetime':
					wherestr[i+'_s']="";
					wherestr[i+'_e']="";
					if($("#"+i).attr('ffct')=='t_between' && !!$("#"+i).val()){//区间范围的需要切割，而且尾头多出了空格
						var st=vs.split('~');
						wherestr[i+'_s']=st[0].substring(0,st[0].length-1);
						wherestr[i+'_e']=st[1].substring(1,st[1].length);
					}else{
						vs?wherestr[i]=vs:wherestr[i]='';
					}
					break;
				default:
					vs?wherestr[i]=vs:wherestr[i]='';
					break;
			}
		});

		if(mName == 'product')wherestr['vCpFl'] = vCpFl;
		table.reload('dhtable', {page: {curr: 1},where:wherestr});
	},1500);
}
/*文本域框
 * parma:obj 操作对象
 * parma:tindex 单据明细中的下标
 * parma:fieldName 目标字段名
 * parma:isReadOnly 只读
 */
function textareaBox(obj,fields,fieldName,isReadOnly){
	var tindex = $(obj).parents('tr').index();
	var readOnly = "", btnObj = [];
	if(isReadOnly){btnObj = ['关闭'];readOnly="readonly"}else{btnObj = ['确定','关闭'];}
	if(isLeadCheck && fields == "vPlanReply"){
		readOnly = "";
		btnObj = ['确定','关闭'];
	}
	if(!listData[tindex][fields])listData[tindex][fields] = "";
	layer.open({
		offset: '10%',
		title: fieldName,
		type: 1,
		area: ['383px', '368px'],
		content: '<textarea id="textareaVal" style="width: calc(100% - 16px);height: calc(100% - 4px);background: #e2eff9;border: 0;text-indent: 2em;padding: 2px 8px;" '+readOnly+'>'+listData[tindex][fields]+'</textarea>',
		btn: btnObj,
		success: function(layero,index){
			layero.find('.layui-layer-content').css('overflow','unset');
		},
		yes: function(index, layero){
			var textareaVal = $("#textareaVal").val();
			listData[tindex][fields]=textareaVal;
			setTableValue('dhtable', tindex, fields, textareaVal);
			if(table.cache.dhtable_c)table.reload('dhtable_c',{data:table.cache.dhtable});//重新渲染弹出框的子表

			if(isLeadCheck && fields == "vPlanReply"){			//周报计划-直接更新数据库上级批复
				var pd=[];
				pd.push({"guid":listData[tindex]['guid'],"vPlanReply":textareaVal})
				var postData = {'infoItems':JSON.stringify(pd)};//转化为json字符串格式
				$.operate.post(moduleUrl+'/pfpost', postData, function(res){
					if(res.code != 0){
						layer.msg(fieldName+'更新失败！');
					}
				});
			}
			layer.close(index);
		}
	});
	$(".detail-edit").prev().css({'width':'90%','display':'inline-block','overflow':'hidden'});		//防止表格中文本域编辑按钮遮挡
}
//选择公司、员工（导入页）
function getMoreForImport(type){
	var flag = true;
	switch(type){
		case 'company':
			var mTitle = '选择公司', mUrl = '/base/company/select';
			break;
		case 'user':
			var mTitle = '选择员工', mUrl = '/system/user/userselect?pagetype=radio', mWidth = '560', mHeight = '465';
			break;
		default:
			flag=false;
			layer.msg('该待选数据类型未处理！');
			break;
	}
	if(flag){
		$.modal.open(mTitle, mUrl, mWidth, mHeight, function(index){
			var res = window["layui-layer-iframe" + index].callbackdata();
			switch(type){
				case 'company':
					$(".layui-layer-page .cid").val(res.vId);
					$(".layui-layer-page .cidName").val(res.vName);
					$(".layui-layer-page .cidName").attr('title',res.vName);
					break;
				case 'user':
					$(".layui-layer-page .bUser").val(res.userId);
					$(".layui-layer-page .bDept").val(res.deptPath);
					$(".layui-layer-page .bUserName").val(res.userName);
					break;
			}
			form.render();
			layer.close(index);
		});
	}
}